angular.module 'list-data-service', []

.factory 'ListDataService', ($http, $rootScope, $q, $ionicPopup, $state) ->
    DataFactory = (name, url) ->
        $watch = {}
        orderData = [] # 保存订单数据
        canLoadMore = true # 是否可以继续加载
        loadingFlag = false #是否正在加载中,避免重复加载
        
        params = {
            size: 10
            page: 0
        }
                        
        
        # 每次切换页面之后，会发送最新的订单数据给该页面的回调函数
        $rootScope.$on '$stateChangeSuccess', ->
            stateName = $state.current.name
            if _.has $watch, stateName
                console.log "change to #{stateName}, send data"
                $watch[stateName] orderData
        
        getData = (setData, innerParams) -> # 如果setData，则会立即将数据传给回调函数
            if loadingFlag
                return {
                    finally: ->
                        console.log 'fetch data error ,now there is an other progress fetching data'
                }
            loadingFlag = true
            _.extend params, innerParams
            console.log params
            $http.get(url, {params: params, loadingAnimation: false})
            .success (resp) ->
                if resp.code == 0
                    if params.page == 0 # 如果是reload
                        orderData = resp.message.content
                        console.log orderData
                    else # 如果是loadMore
                        console.log 'load more in------------', resp.message.content
                        orderData.push.apply orderData, resp.message?.content
                    if resp.message?.content?.length < params.size then canLoadMore = false
                    else canLoadMore = true
                    params.page += 1 # 起始点增加返回的数据长度
                else
                    canLoadMore = false
                stateName = $state.current.name
                if setData and _.has $watch, stateName
                    console.log "call back #{$state.current.name}"
                    console.log $watch
                    $watch[stateName] orderData
                loadingFlag = false
            .error ->
                loadingFlag = false
                #处理没网环境下重复加载bug
                canLoadMore = false
                $ionicPopup.alert {title: '哎呀!', template: '您的网络又调皮了'}
                
        
        canLoadMore: ->
            if canLoadMore == undefined then false
            else canLoadMore

# 需要更新数据时，请调用reload方法
# 如果setData为true，reload方法会调用当前view对应state里的回调函数
        reload: (innerParams = undefined, setData = false) ->
            params.page = 0
            getData(setData, innerParams)
        
        loadMore: (innerParams = undefined, setData = true) ->
            console.log 'loadMore data'
            getData(setData, innerParams)

# 需要获取order数据，请传递一个回调函数来调用watch方法，
# watch方法会立即将数据给予调用者
        watch: (func) ->
            if !_.isFunction(func)
                throw "watch param is not a function!"
            key = $state.current.name
            $watch[key] = func
            console.log "key: #{key}\t$watch size: #{_.keys($watch).length}"
            func orderData
            
            # 如果调用了watch方法，一定要监听$scope的$destory事件，
            # 并在$destory事件发生时调用这里返回的函数，
            # 不然会发生内存泄露
            -> delete $watch[key]
    
    pool = {}
    
    init: (name, url) ->
        if _.isEmpty(url) then throw '初始化dataFactory对象需要指定url'
        obj = new DataFactory(name, url)
        pool[name] = obj
    get: (name) ->
        if _.has(pool, name)
            return pool[name]
        else
            throw "没有为dataFactory对象初始化#{name}"

.run (ListDataService) ->
    ListDataService.init 'orderList', '/crewOrder'
